﻿/// <reference path="../interfaces/ireferenceuniversesservice.ts" />
/// <reference path="../interfaces/iuploaderrorlog.ts" />
/// <reference path="../../../../typings/angularjs/angular.d.ts" />
/// <reference path="../../../interfaces/inotificationfactory.ts" />
/// <reference path="../../../interfaces/istaticobjects.ts" />
/// <reference path="../interfaces/ireferenceuniverseclass.ts" />

module Sustainalytics.EsgRatings {
    export class ReferenceUniversesController {
        public referenceUniversesService: IReferenceUniversesService;
        // controller scope
        public $scope: ng.IScope;
        // services
        private $q: ng.IQService;
        private $location: ng.ILocationService;
        private notificationFactory: INotificationFactory;
        private staticObjects: IStaticObjects;

        // specifies whether current controller is in loading state
        public isLoading: boolean;
        public isValid :boolean;
        public errorMessage: string;
        public uploadProgress: number;
        public uploadProgressExisting: number;
        public newReferenceUniverseName: string;
        public selectedReferenceUniverse: IReferenceUniverse;
        public existingReferenceUniverses: IReferenceUniverse[];
        public uploadDetails: string;

        //private inputFile: PIInputFileDto;
        private selectedFile: File;
        private existingSelectedFile: File;

        constructor($scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, $http: ng.IHttpService, ReferenceUniversesService, notificationFactory: INotificationFactory, staticObjects) {


           
            var ctx = this;
            ctx.referenceUniversesService = ReferenceUniversesService;
            ctx.$scope = $scope;
            ctx.$q = $q;
            ctx.$location = $location;
            ctx.notificationFactory = notificationFactory;
            ctx.staticObjects = staticObjects;
            ctx.uploadProgress = -1;
            ctx.uploadProgressExisting = -1;

            
            ctx.referenceUniversesService.getReferenceUniverses()
                .then(data => {
                    ctx.existingReferenceUniverses = data;
                if (data.length > 0) {
                    ctx.selectedReferenceUniverse = data[0];
                }
                
            });
            $scope['referenceUniverses'] = ctx;
        }

        public onSelectExcel($files): any {

            var ctx = this;

            ctx.selectedFile = null;
            var file = $files[0]; // html assures is just 1
            if (file && (file.type != "application/vnd.ms-excel" && file.type != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
                ctx.uploadDetails = null;
                ctx.showErrorCode(2200);
            }
            else if (file) {

                ctx.selectedFile = file;
            }
        }
        public onExistingSelectExcel($files): any {

            var ctx = this;

            ctx.existingSelectedFile = null;
            var file = $files[0]; // html assures is just 1
            if (file && (file.type != "application/vnd.ms-excel" && file.type != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
                ctx.uploadDetails = null;
                ctx.showErrorCode(2200);
            }
            else if (file) {

                ctx.existingSelectedFile = file;
            }
        }

        public uploadNewReferenceUniverse() {
            var ctx = this;
            var refFound = false;

            $.each(ctx.existingReferenceUniverses, (index, element:IReferenceUniverse) => {
                if (element.name.toLowerCase() == ctx.newReferenceUniverseName.toLowerCase()) {
                    refFound = true;
                }
            });

            if (refFound) {
                alert("The reference universe '" + ctx.newReferenceUniverseName + "' already exists!");
                return;
            }
            if (ctx.selectedFile) {
                var formData = { universeName: ctx.newReferenceUniverseName}
                ctx.uploadProgress = 0;
                var promise = ctx.referenceUniversesService.uploadReferenceUniverse(ctx.selectedFile, formData, ctx.uploadProgress);
                promise.then(
                    // success 
                    (data:any) => { // handles  validation /operation result
                        ctx.$scope.$evalAsync(() => {
                            console.log(data);

                            //ctx.isValid = data.isValid;
                            //ctx.errorMessage = data.errorMessage;

                            if (data == null || data == undefined || data == '') {
                                ctx.notificationFactory.success('Upload succeeded. Data in file is valid.');
                                //clearform
                                ctx.selectedFile = null;
                                ctx.newReferenceUniverseName = '';
                                ctx.uploadDetails = null;
                                
                            } else {
                                ctx.notificationFactory.error('', 'Upload succeeded. Data in file not valid.');
                                if (data.returnData) {
                                    ctx.uploadDetails = data.returnData;
                                }
                            }

                            ctx.uploadProgress = -1;
                        });

                    }
                    //error
                    //(data: { code: number}) => {
                    //    ctx.showErrorCode(2300);
                    //    ctx.uploadProgress = -1;
                    //}
                );
            }
        }

        public uploadExistingReferenceUniverse() {
            var ctx = this;
            if (ctx.existingSelectedFile) {
                var formData = { universeName: ctx.selectedReferenceUniverse.name }
                ctx.uploadProgressExisting = 0;
                var promise = ctx.referenceUniversesService.uploadReferenceUniverse(ctx.existingSelectedFile, formData, ctx.uploadProgress);
                promise.then(
                    // success 
                    (data: any) => { // handles  validation /operation result
                        ctx.$scope.$evalAsync(() => {
                            console.log(data);

                            //ctx.isValid = data.isValid;
                            //ctx.errorMessage = data.errorMessage;

                            if (data == null || data == undefined || data == '') {
                                ctx.notificationFactory.success('Upload succeeded. Data in file is valid.');
                                //clearform
                                ctx.existingSelectedFile = null;
                                ctx.uploadDetails = null;

                            } else {
                                ctx.notificationFactory.error('', 'Upload succeeded. Data in file not valid.');
                                if (data.returnData) {
                                    ctx.uploadDetails = data.returnData;
                                }
                            }

                            ctx.uploadProgressExisting = -1;
                        });

                    }
                //error
                //(data: { code: number}) => {
                //    ctx.showErrorCode(2300);
                //    ctx.uploadProgressExisting = -1;
                //}
                    );
            }
        }

        private showErrorCode(code: number) {
            var ctx = this;
            var msg = ctx.staticObjects.getMessageByInternalCode(code);
            ctx.notificationFactory.error('', msg);
        }
    }

    // register controller with Tools Angular module
    angular.module('Sustainalytics.EsgRatings').controller('ReferenceUniversesController', ($scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, $http: ng.IHttpService, ReferenceUniversesService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects) => new ReferenceUniversesController($scope, $q, $location, $http, ReferenceUniversesService, notificationFactory, staticObjects));
} 